/*
 * Copyright (c) jiucheng.org
 */
package org.jiucheng.template;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.jiucheng.template.grammar.Root;

/**
 * 
 * @author jiucheng jiucheng.org@gmail.com
 *
 */
public class Template {

    private static final Map<String, Root> pool = new ConcurrentHashMap<String, Root>();
    private static GrammarManager grammarManager = new GrammarManager();

    public static void setGrammarContent(GrammarContent grammarContent) {
        grammarManager.setGrammarContent(grammarContent);
    }

    public static String get(Map<String, Object> context, String filePath) {
        filePath = filePath.replaceAll("\\\\", "/").trim();
        Root root = getRoot(filePath);
        StringBuilder sb = new StringBuilder();
        root.exec(context, sb);
        return sb.toString();
    }

    public static void clear(String filePath) {
        filePath = filePath.replaceAll("\\\\", "/").trim();
        if (pool.containsKey(filePath)) {
            pool.remove(filePath);
        }
    }

    public static void putClass(String alia, Class<?> clazz) {
        grammarManager.putClass(alia, clazz);
    }

    public static Class<?> getClass(String alia) {
        return grammarManager.getClass(alia);
    }

    private static Root getRoot(String filePath) {
        Root root = pool.get(filePath);
        if (root == null) {
            root = grammarManager.parse(filePath);
            pool.put(filePath, root);
        }
        return root;
    }
}
